#include "uimainwindow.h"
#include "ui_uimainwindow.h"

UIMainWindow::UIMainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::UIMainWindow)
{
    ui->setupUi(this);
    ui->statusbar->showMessage("必须由自己构建状态栏,s_bar");
    //设置主题
    QFile file(QString("://%1").arg("Cyan_theme"));
    file.open(QIODevice::ReadOnly);
    this->setStyleSheet( file.readAll());
    file.close();
    Init_UIMainWindow();
}

//设置表格数据
void UIMainWindow::Init_UIMainWindow()
{
    QStringList sl;
    sl<<"姓名"<<"年龄"<<"成绩"<<"删除列";
    //设置列数
    ui->tableWidget->setColumnCount(sl.size());
    //设置表头
    ui->tableWidget->setHorizontalHeaderLabels(sl);

    //设置静态行数
//    ui->tableWidget->setRowCount(10);
    //插入动态空行
#if 0//最开始学习表格时候的案例输入
      ui->tableWidget->insertRow(0);
    //设置数据
    ui->tableWidget->setItem(0,0,new QTableWidgetItem("wyf"));
    //给表格里面加入控件setCellWidget
    QSpinBox *sbox = new QSpinBox();
    sbox->setRange(0,100);
    ui->tableWidget->setCellWidget(0,1,sbox);
    QComboBox *cbox = new QComboBox();
    cbox->addItems(QStringList()<<"男"<<"女");
    ui->tableWidget->setCellWidget(0,2,cbox);
#endif
}

UIMainWindow::~UIMainWindow()
{
    delete ui;
}

//不需要connect连接
void UIMainWindow::on_loginAction_triggered()
{
    loginw = new login_window;
    //设置窗口关闭的时候资源回收
    loginw->setAttribute(Qt::WA_DeleteOnClose);
    loginw->show();
}

//设置颜色
void UIMainWindow::on_colorAct_triggered()
{
    QColor co = QColorDialog::getColor(Qt::black,this,"color",QColorDialog::ShowAlphaChannel);
    ui->textEdit->setTextColor(co);
}

//模态对话框---继承了父类，不需要手动释放
void UIMainWindow::on_modalAct_triggered()
{
    //    QDialog *dlg= new QDialog(this);
    QDialog *dlg = new QDialog(this);
    dlg->open();  //窗口级模态，只会影响父界面，不会影响点击其他界面。
    //    dlg->exec();  //应用程序级模态
}

//非模态对话框
void UIMainWindow::on_modelessAct_triggered()
{
    QDialog *dlg = new QDialog;
    dlg->setAttribute(Qt::WA_DeleteOnClose);//
    dlg->show();
}

//设置字体---getFont()---自己完成
void UIMainWindow::on_fontAction_triggered()
{
    int ft_size = QInputDialog::getInt(this,"输入标题","输入框");
    QFont ft = ui->textEdit->font();
    ft.setPointSize(ft_size);
    ui->textEdit->setFont(ft);
#if 0//两行显示
    ui->textEdit->append("字体已设置为：");
    ui->textEdit->append(QString::number(ft_size));
#endif
    //一行显示
    ui->textEdit->setText(QString("字体已设置为: %1").arg(ft_size));
}

//打开文件
void UIMainWindow::on_openAction_triggered()
{
    /*
     * 1、实例化QFile对象
     * 2、调用open 打开文件
     * 3、调用read readAll readLine读文件
     * 4、处理读取的数据
     * 5、关闭文件
     */
    QString filename =  QFileDialog::getOpenFileName(this,"file1",".",
                                                     "all(*.*);;"
                                                     "Images (*.png *.xpm *.jpg);;"
                                                     "Text files (*.txt)");
    QFile file(filename);
    bool success = file.open(QIODevice::ReadOnly);
    if(!success)
    {
        QMessageBox::warning(this,"open","open failed",QMessageBox::Ok);
        return;
    }
    //读操作
    QByteArray text = file.readAll();
    file.close();

    ui->textEdit->append(text);
}

//消息对话框
void UIMainWindow::on_msgAction_triggered()
{
    //    int ret = QMessageBox::critical(this,"错误","这是个错误对话框",
    //                          QMessageBox::Yes,
    //                          QMessageBox::No);

    int ret = QMessageBox::information(this,"info","information",
                                       QMessageBox::Yes|QMessageBox::No);
    if(ret == QMessageBox::Yes)
    {
        ui->textEdit->append("yes");
    }
    else if(ret == QMessageBox::No)
    {
        ui->textEdit->append("no");
    }
}

//错误对话框
void UIMainWindow::on_errorAction_triggered()
{
    QErrorMessage* msg = QErrorMessage::qtHandler();
    msg->showMessage("error test");
    //需要手动调用 show  exec 显示对话框
    msg->show();
}

//输入对话框
void UIMainWindow::on_inputAction_triggered()
{
    int res = QInputDialog::getInt(this,"inputInt","input int");
    //sprintf
    ui->textEdit->append(QString("int val:%1").arg(res));
}

//向导对话框
void UIMainWindow::on_winzardAction_triggered()
{
    QWizard* win = new QWizard(this);
    QWizardPage *p1 =new QWizardPage;
    QLabel * lb1 =new QLabel("page1",p1);

    QWizardPage *p2 =new QWizardPage;
    QLabel * lb2 =new QLabel("page2",p2);
    win->addPage(p1);
    win->addPage(p2);
    win->show();
}

//进度条对话框
void UIMainWindow::on_progressAction_triggered()
{
    QProgressDialog *pdlg =new QProgressDialog(this);
    pdlg->setRange(0,100);
    pdlg->setValue(5);
    pdlg->show();
}

void UIMainWindow::on_saveAction_triggered()
{
    /*
     * 1、实例化QFile对象
     * 2、调用open 打开文件
     * 3、准备写入文件的数据
     * 4、调用write 写入文件
     * 5、关闭文件
     */
    QString filename =  QFileDialog::getOpenFileName(this,"file1",".",
                                                     "all(*.*);;"
                                                     "Images (*.png *.xpm *.jpg);;"
                                                     "Text files (*.txt)");
    QFile file(filename);
    bool success = file.open(QIODevice::WriteOnly);
    if(!success)
    {
        QMessageBox::warning(this,"open","open failed",QMessageBox::Ok);
        return;
    }
    //获取多行文本框的内容
    QString text = ui->textEdit->toPlainText();
    //写操作
    file.write(text.toUtf8());
    file.close();
}



void UIMainWindow::on_textReadAction_triggered()
{
    /*
     * 1、实例化QFile对象
     * 2、关联QFile 实例化QTextStream 对象
     * 3、>> 读文件
     * 4、显示内容到文本框
     * 5、关闭文件
     */

    QFile file(QFileDialog::getOpenFileName(this));
    file.open(QIODevice::ReadOnly);
    QTextStream in(&file);

    QString text;
    while(!in.atEnd())
    {
        in>>text;
        ui->textEdit->append(text);
    }

    file.close();
}

void UIMainWindow::on_textWriteAction_triggered()
{

}



void UIMainWindow::on_dataWirteaction_triggered()
{
    /*
     * 1、实例化QFile对象
     * 2、关联QFile 实例化QDataStream 对象 打开文件
     * 3、<< 写文件
     * 5、关闭文件
     */
    QFile file(QFileDialog::getOpenFileName(this));
    file.open(QIODevice::WriteOnly);
    QDataStream out(&file);
    QString name("bbl");
    int age = 10;
    double score = 9;
    out<<name<<age<<score;
    file.close();
}

void UIMainWindow::on_dataReadaction_triggered()
{

}
//网络设置界面
void UIMainWindow::on_netAction_triggered()
{
    my_netset = new Netset();
    my_netset->setAttribute(Qt::WA_DeleteOnClose);
    my_netset->show();
}


//获取登录数据——1
void UIMainWindow::on_luruAction_triggered()
{
    /*
     * 1、实例化FormWindow 对象
     * 2、关闭窗口回收资源
     */
    FormWindow *fwin = new FormWindow;
    fwin->setAttribute(Qt::WA_DeleteOnClose);
    fwin->show();
    connect(fwin,&FormWindow::sendPerson,this,&UIMainWindow::handlerPerson);
}
//获取登录数据——2
void UIMainWindow::handlerPerson(QString name, int age, QString gender)
{
    //在textedid里面显示
    ui->textEdit->append(name);
    ui->textEdit->append(QString::number(age));
    ui->textEdit->append(gender);

    //获取当前表格的行数在Tablewidget表格里面显示
    int curRow = ui->tableWidget->rowCount();
    ui->tableWidget->insertRow(curRow);
    ui->tableWidget->setItem(curRow,0,new QTableWidgetItem(name));
    ui->tableWidget->setItem(curRow,1,new QTableWidgetItem(QString::number(age)));
    ui->tableWidget->setItem(curRow,2,new QTableWidgetItem(gender));
    QPushButton *btn = new QPushButton("删除");
    ui->tableWidget->setCellWidget(curRow,3,btn);

    connect(btn,&QPushButton::clicked,this,&UIMainWindow::removeRow);
//   connect(btn,&QPushButton::clicked,this,[=](){
//       ui->tableWidget->removeRow(curRow);
//   });
}

void UIMainWindow::removeRow()
{
    int row = ui->tableWidget->rowCount();
    ui->tableWidget->removeRow(row);
    ui->tableWidget->setFocus();
}

//根据combox设置qss外观样式
void UIMainWindow::on_comboBox_currentIndexChanged(const QString &arg1)
{
    QFile file(QString("://%1").arg(arg1));
    file.open(QIODevice::ReadOnly);
    this->setStyleSheet( file.readAll());
    file.close();
}


//进入串口界面
void UIMainWindow::on_serialportAction_triggered()
{
    my_serial = new serialwindow;
    my_serial->setAttribute(Qt::WA_DeleteOnClose);
    my_serial->show();
}

//删除表格的某一行
void UIMainWindow::on_removeAction_triggered()
{
    int curRow = ui->tableWidget->currentRow();
    ui->tableWidget->removeRow(curRow);
    ui->tableWidget->setFocus();
}

//数据库中添加数据
void UIMainWindow::on_dbAddAction_triggered()
{
    /*
     * 1、准备sql
     * 2、实例化QsqlQuery 对象
     * 3、执行sql  exec
     */
    QString sql = "INSERT INTO stu (name,age,score) VALUES('bob',19,56);";

    QSqlQuery query;

    if(query.exec(sql))
    {
        QMessageBox::warning(this,"warn","插入数据成功",QMessageBox::Ok);
    }
    else
    {
        QMessageBox::warning(this,"warn","插入数据失败:"+query.lastError().text(),QMessageBox::Ok);
    }
}

//数据库中移除数据！！！
void UIMainWindow::on_removeAction_2_triggered()
{
    FormWindow *fw = new FormWindow;
    fw->setAttribute(Qt::WA_DeleteOnClose);
    fw->show();
    connect(fw,
            static_cast<void(FormWindow::*)(QString,int ,QString)>(&FormWindow::sendPerson),
            [&](QString name,int age ,QString gen){
        QString sql = QString ("delete from stu where name = '%1'").arg(name);
        QSqlQuery query(sql);

        if(query.exec())
        {
            QMessageBox::warning(this,"warn","删除数据成功",QMessageBox::Ok);
        }
        else
        {
            QMessageBox::warning(this,"warn","删除数据失败:"+query.lastError().text(),QMessageBox::Ok);
        }
    });
}
//数据库中查询数据
void UIMainWindow::on_sqlQueryAction_triggered()
{
    QSqlQuery query("select * from stu");
    int rows = ui->tableWidget->rowCount();
    while(query.next())
    {
        ui->tableWidget->insertRow(rows);
        ui->tableWidget->setItem(rows,0, new QTableWidgetItem(query.value(0).toString()));
        ui->tableWidget->setItem(rows,1, new QTableWidgetItem(query.value(1).toString()));
        ui->tableWidget->setItem(rows,2, new QTableWidgetItem(query.value(2).toString()));
    }
}
#if 0//经典错误,栈区的问题
//数据库修改数据
void UIMainWindow::on_updateAction_triggered()
{
    bool ok;
    QString oldName = QInputDialog::getText(this, "原名字", "请输入原名字:", QLineEdit::Normal, "", &ok);

    if (!ok || oldName.isEmpty()) {
        QMessageBox::warning(this, "输入错误", "名字不能为空", QMessageBox::Ok);
        return;
    }

    QString checkSql = QString("SELECT * FROM stu WHERE name = '%1'").arg(oldName);
    QSqlQuery checkQuery;
    if (checkQuery.exec(checkSql)) {
        if (!checkQuery.next()) {
            QMessageBox::warning(this, "未找到名字", "该名字不存在于数据库中", QMessageBox::Ok);
            return;
        }
    } else {
        qDebug() << "查询错误：" << checkQuery.lastError().text();
        return;
    }


    // 弹出修改窗口
    FormWindow *fw = new FormWindow;
    fw->setAttribute(Qt::WA_DeleteOnClose);
    fw->show();

    // 连接信号与槽函数，在 FormWindow 中修改数据
    connect(fw,
            static_cast<void(FormWindow::*)(QString, int, QString)>(&FormWindow::sendPerson),
            [&](QString name, int age, QString gen){
                qDebug() << "接收到的新的数据：" << "name: " << name << " age: " << age << " gen: " << gen;

                // 使用 oldName 作为条件来更新数据库中的记录
                QString sql = QString("UPDATE stu SET name = '%1', age = %2 WHERE name = '%4'").arg(name,QString::number(age),oldName);
                qDebug() << sql;
                QSqlQuery query;
                if (query.exec(sql)) {
                    qDebug() << "数据更新成功";
                    QMessageBox::information(this, "Success", "数据修改成功", QMessageBox::Ok);
                } else {
                    qDebug() << "数据更新失败，错误信息：" << query.lastError().text();
                    QMessageBox::warning(this, "Error", "数据修改失败: " + query.lastError().text(), QMessageBox::Ok);
                }
    });
}

#endif






